//
//  SWStatusDAL.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/4/9.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit


/*
加载微博数据,有可能从本地,也有可能从网络加载
1.查看本地是否有数据 *
2.如果本地有数据直接返回
3.本地没有数据发送网络请求
4.获取到数据后保存到数据库 *
5.将获取的数据返回给调用的人
*/

class SWStatusDAL: NSObject {
    
    static let sheadDAL = SWStatusDAL()
    
    ///利用DAL加载微博数据
    func loadStatus(since_id: Int,  max_id: Int ,dalLoadStatusCallBack: (statuses:[[String: AnyObject]]? , error: NSError?) -> ()) {
        
        loadCacheStatus(since_id, max_id: max_id) { (statuses) -> () in
            //1.先查询数据库有没有
            if statuses != nil && statuses?.count > 0 {
                //能加载到本地微博数据
                print("能加载到本地数据: \(statuses?.count)条")
                //有数据直接回调
                dalLoadStatusCallBack(statuses: statuses, error: nil)
                return
            }
            //来到这里说明数据库没有微博数据
            //2.没有数据就调用网络工具类发送请求数据
            SWNetWorkTool.sharedNetWorkTool.loadStatus(since_id, max_id: max_id, finished: { (result, error) -> () in
                
                if error != nil {
                    print("DAL网络请求error: \(error)");
                    return
                }
                //拿出微博数组
                if let statuses = result?["statuses"] as? [[String : AnyObject]]{
                    //保存到数据库
                    self.saveStatuses(statuses)
                    //获取成功回调
                    dalLoadStatusCallBack(statuses: statuses, error: nil)
                }else {
                    //获取数据失败
                    dalLoadStatusCallBack(statuses: nil, error: nil)
                }
            })
        }
    }
    
    //查询本地缓存的微博
    private func loadCacheStatus(since_id: Int,  max_id: Int , loadCacheStatusCallBack: (statuses:[[String: AnyObject]]?) -> () ) {
    
        var sql = "SELECT status_id , status , user_id FROM T_Status \n"
        
        let uid = SWUserAccountViewModel.sharedInstance.userAccount!.uid!
        
        if since_id > 0 {
            //下拉刷新，加载比since_id大的微博
            sql += "WHERE status_id >  \(since_id) AND user_id = \(uid) \n"
            
        }else if max_id > 0 {
            //上啦加载 查找比我现在传进来小的_id
            sql += "WHERE status_id < \(max_id) AND user_id = \(uid) \n"
        }
        //只查询20条
        sql += " ORDER BY status_id DESC LIMIT 20;"
        
        print("拼接的sql: \(sql)")
        
        
        SWSQliteManager.sheadManager.queue.inDatabase { (db) -> Void in
            //执行sql语句
            guard let resultSet = db.executeQuery(sql) else {
                print("数据库没有微博数据")
                loadCacheStatusCallBack(statuses: nil)
                return
            }
            
            //来到这就是数据库有微博缓存
            //加载到本地的字典数组
            var statuses = [[String : AnyObject]]()
            
            //循环数据库里的没一条信息
            while resultSet.next() {
            
                let status = resultSet.stringForColumn("status")
                //String -> data ->字典
                let data = status.dataUsingEncoding(NSUTF8StringEncoding)
                
                let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject]
                //加到数组
                statuses.append(dict)
            }
            //加载完成回调
            loadCacheStatusCallBack(statuses: statuses)
        }
    }
    
    /**
     保存微博到数据库
    - parameter statuses: 微博数组
    */
    private func saveStatuses(statuses: [[String : AnyObject]] ) {
        //用户id
        let uid = SWUserAccountViewModel.sharedInstance.userAccount?.uid
        
        let sql = "INSERT OR REPLACE INTO T_Status (status_id, status, user_id) VALUES (?, ?, ?)"
        //执行sql
        SWSQliteManager.sheadManager.queue.inTransaction { (db, rollBack) -> Void in
            
            //将字典 -> data -> string 
            
            for dict in statuses {
                //微博status_id
                let id = dict["id"] as! Int
                
                let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
                //微博内容
                let string = String(data: data, encoding: NSUTF8StringEncoding)
                //执行sql
                db.executeUpdate(sql, id, string!, uid!)
            }
            print("保存到数据库完成: \(statuses.count)条");
            
        }
        
    }
    
}
